<?php
/**
 * Created by: i@fedax.cn
 * Date: 2018/7/29 0:16
 */

namespace app\admin\model;


use think\Db;

class Family extends DataBase
{
    protected $name = 'family';
    protected $autoWriteTimestamp = true;

    public function getStatusAttr($value)
    {
        $status = [1=>'可用',2=>'禁用'];
        return $status[$value];
    }
    public function getTypeAttr($value)
    {
        $status = [1 => '通过',2=>'审核中',3=>'复审',4=>'已解散'];
        return $status[$value];
    }

    public function getDataList()
    {
        $page_config = array(
            'page' => input('get.offset', 1),
            'list_rows' => input('get.limit', 10),
        );
        $where = [];
        if(input('key')=='nickname' && !empty(input('value'))){
            $where[] = ['b.nickname','=',input('value')];
        }elseif(input('key')=='f_name' && !empty(input('value'))){
            $where[] = ['a.f_name','=',input('value')];
        }elseif(input('key')=='u_id' && !empty(input('value'))){
            $where[] = ['b.u_id','=',input('value')];
        }
        $data= $this
            ->alias('a')
            ->field('a.id,a.user_id,a.f_name,a.f_signature,a.f_liveness,a.create_time,a.status,a.type,b.u_id,b.nickname')
            ->join('users b','a.user_id = b.id','left')
            ->where($where)
            ->order('a.create_time DESC')
            ->paginate($page_config);
        foreach($data as $key =>$value){
            $data[$key]['sum'] = FamilyMembers::where('family_id='.$value['id'])->count('family_id');
//            $data[$key]['f_name'] = get_user_name();
//            $data[$key]['nickname'] = get_user_name();
        }
        return $data;
    }
    //家族流水
    public function getFamilyDataList($page_config,$where,$map,$condition)
    {
        $data =  $this->where($map)->paginate($page_config);
        $userModel = new User();
        $giftRecordModel = new GiftRecord();
        $roomModel = new Room();

        foreach($data as  $key => $value){
            $userInfo = $userModel->where('id','=',$value['user_id'])->where($condition)->find();
            $roomInfo = $roomModel->where('r_id','=',$value['user_id'])->find();
            $sum = $giftRecordModel ->where($where)->where('room_id','=',$roomInfo['id'])->sum('gift_price');
            $data[$key]['id'] = $value['id'];
            $data[$key]['f_name'] = $value['f_name'];
            $data[$key]['u_id'] = $userInfo['u_id'];
            $data[$key]['nickname'] = $userInfo['nickname'];
            $data[$key]['sum'] = $sum;
        }
        return $data;
//
    }

    /**
     * Notes: 家族流水数据
     * User: 王俊成
     * Date: 2018/11/2
     * Time: 9:52
     * @return \think\Paginator
     */
    public function familyFlowingData(){
        $page_config = array(
            'page' => input('pageNum', 1),
            'list_rows' => input('list', 10),
        );
        $keyWords = input('get.keyWords');
        $map = [
            ['status','=',1],
            ['type','=',1]
        ];
        if(!empty($keyWords) || $keyWords == '0'){
            $key = input('get.key');
            if($key == 'id')
                $map[] = ['id','=',$keyWords];
            if($key == 'f_name')
                $map[] = [$key,'like','%'.$keyWords.'%'];
            if($key == 'u_id'){
                $user_id = User::where($key,'=',$keyWords)->value('id');
                $map[] = ['user_id','=',$user_id];
            }
            if($key == 'nickname'){
                $user_id = User::where($key,'=',$keyWords)->value('id');
                $map[] = ['user_id','=',$user_id];
            }
        }

//        $data = $this->alias('a')->fieldRaw('a.id,f_name,a.user_id,b.u_id,nickname,SUM(c.gift_price) as flowing_num')
//            ->leftJoin('users b','a.user_id=b.id')
//            ->leftJoin('gift_record c','a.id=c.receive_family_id')
//            ->group('c.receive_family_id')->order('flowing_num DESC')
//            ->where($map)->paginate($page_config);
//        if($data){
//            foreach($data as $key => $value){
//                $value['nickname'] = conversionEmojiName($value['nickname']);
//                $value['flowing_url'] = 'http://user.yuliaokaihei.com/index.php/public/familyFlowing/id/'.encode($value['id']);
//                $value['liveness_url'] = 'http://user.yuliaokaihei.com/index.php/public/livenessFlowing/id/'.encode($value['id']);
//                //族长链接使用
//                $value['encode_id'] = encode($value['id']);
//                $value['key'] = encode($value['encode_id']);
//                $data[$key] = $value;
//            }
//        }
        $data = $this->field('id,user_id,f_name')->where($map)->paginate($page_config);

        foreach($data as $key => $value){

            $userInfo = User::field('u_id,nickname')->where('id','=',$value['user_id'])->find();
            $data[$key]['u_id'] = $userInfo['u_id'];
            $data[$key]['nickname'] = conversionEmojiName($userInfo['nickname']);
            $data[$key]['flowing_url'] = 'http://user.quniuyuyin.com/index.php/public/familyFlowing/id/'.encode($value['id']);
            $data[$key]['liveness_url'] = 'http://user.quniuyuyin.com/index.php/public/livenessFlowing/id/'.encode($value['id']);
            //族长链接使用
            $value['encode_id'] = encode($value['id']);
            $value['key'] = encode($value['encode_id']);
            $data[$key] = $value;
        }

        return $data;
    }

    /**
     * Notes: 获取家族月流水详情
     * User: 王俊成
     * Date: 2018/11/2
     * Time: 14:09
     * @return array
     */
    public function familyFlowingInfoData(){
        $familyId = input('get.familyId');
        $queryTime = input('get.queryTime');
        if(!empty($queryTime) && $queryTime != date('Y-m')){
            if(strtotime($queryTime) > time()){
                return ['resultCode'=>110,'resultData'=>null,'resultDes'=>'查询结果集为空！'];
            }
            else{
                $startTime = strtotime($queryTime.'-01');
                $endTime = strtotime(date('Y-m-d',strtotime("$queryTime + 1 month - 1 day")).' 23:59:59');
            }
        }
        else{
            $startTime = strtotime(date('Y-m').'-01');
            $endTime = time();
        }
        $dayNum = ceil(($endTime - $startTime) / (3600 * 24));
        $data = [];
        for($i = 0;$i < $dayNum;$i++){
            $arr['date'] = date('Y-m-d',$startTime + 3600 * 24 * $i);
            $arr['diamonds'] = GiftRecord::where([['receive_family_id','=',$familyId],['create_time','between',[strtotime($arr['date']),strtotime($arr['date'].' 23:59:59')]]])->sum('gift_price');
            $data[] = $arr;
        }
        return ['resultCode'=>100,'resultData'=>$data,'resultDes'=>'查询成功！'];
    }

    /**
     * Notes: 家族天流水详情
     * User: 王俊成
     * Date: 2018/11/2
     * Time: 14:46
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function familyFlowingDay(){
        $pageConfig = [
            'list_rows' => 25,
            'page' => input('get.page',1),
            'query' => [
                'familyId' => input('get.familyId'),
                'dates' => input('get.dates')
            ]
        ];
        return GiftRecord::where([['receive_family_id','=',input('get.familyId')],['create_time','between',[strtotime(input('get.dates')),strtotime(input('get.dates').' 23:59:59')]]])
            ->fieldRaw('receive_user_id,receive_family_id,SUM(gift_price) as flowing_num')
            ->group('receive_user_id')->order('flowing_num DESC')
            ->paginate($pageConfig);
    }

    /**
     * Notes: 家族天流水成员收礼记录数据
     * User: 王俊成
     * Date: 2018/11/3
     * Time: 10:18
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function familyFlowingDayDetail(){
        $familyId = input('get.familyId');
        $userId = input('get.userId');
        $dates = input('get.dates');
        $pageConfig = [
            'list_rows' => 25,
            'page' => input('get.page',1),
            'query' => [
                'familyId' => $familyId,
                'userId' => $userId,
                'dates' => $dates
            ]
        ];
        return GiftRecord::where([['receive_family_id','=',$familyId],['create_time','between',[strtotime($dates),strtotime($dates.' 23:59:59')]],['receive_user_id','=',$userId]])
            ->field('send_user_id,receive_user_id,gift_type,num,gift_price,create_time')->order('create_time DESC')->paginate($pageConfig);
    }

    /**
     * Notes: 家族上周流水数据导出
     * User: 王俊成
     * Date: 2018/11/3
     * Time: 14:27
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function familyFlowingExport(){
        $startTime = strtotime(date('Y-m-d',strtotime('last week')));
        $endTime = $startTime + 7 * 24 * 3600;
        //获取数据
        $data = GiftRecord::where([['receive_family_id','<>',0],['create_time','between',[$startTime,$endTime]]])->whereNotNull('receive_family_id')
            ->fieldRaw('receive_family_id,SUM(gift_price) as flowing_num,SUM(get_money) as all_money')
            ->group('receive_family_id')->order('flowing_num DESC')->having('SUM(gift_price)>0')->select()->toArray();

        if($data){

            foreach($data as $key => $value){

                $familyInfo = $this->where('id','=',$value['receive_family_id'])->find();
                if($familyInfo['type'] == '通过' && $familyInfo['status'] == '可用'){
                    $value['family_name'] = $familyInfo['f_name'];
                    $value['heads_name'] = get_user_name($familyInfo['user_id']);
                    $value['heads_uid'] = get_uid($familyInfo['user_id']);
                    $aliPayInfo = WithdrawalInfo::where('user_id',$familyInfo['user_id'])->field('alipay_card,alipay_name')->find();
                    if($aliPayInfo){
                        $value['alipay_name'] = $aliPayInfo['alipay_name'];
                        $value['alipay_card'] = $aliPayInfo['alipay_card'];
                    }
                    else{
                        $value['alipay_name'] = '';
                        $value['alipay_card'] = '';
                    }
                    $value['scale'] = '5%';
                    $value['all_money'] = $value['flowing_num'] * 0.1 * 0.05;
                    //获取家族七日流水数据
                    for($i = 0;$i < 7;$i++){
                        $dates = date('Y-m-d',$startTime + $i * 24 * 3600);
                        $value[$dates] = GiftRecord::where([['receive_family_id','=',$value['receive_family_id']],['create_time','between',[strtotime($dates),strtotime($dates.' 23:59:59')]]])
                            ->sum('gift_price');
                    }
                    $data[$key] = $value;
                }
                else{
                    unset($data[$key]);
                    continue;
                }

            }
            $data = array_merge($data);
        }
        $fileName = '家族流水';
        $remarkData = ['家族流水'];
        $cellTitle = [
            ['family_name','家族名'],
            ['heads_name','族长'],
            ['heads_uid','族长ID'],
            ['alipay_name','支付宝姓名'],
            ['alipay_card','支付宝账号'],
            ['scale','返现比例'],
            ['all_money','金钱'],
            ['flowing_num','上周流水（钻石）'],
        ];
        for($i = 0;$i < 7;$i++){
            $dates = date('Y-m-d',$startTime + $i * 24 * 3600);
            $cellTitle[] = [$dates,$dates];
        }
        $excelObj = new \app\common\api\Excel();
        $excelObj->exportExcel($fileName,$remarkData,$cellTitle,$data);
    }

    /**
     * @return bool
     * @user shuaisuhias wu
     * @date 2018/12/11
     * @time 15:26
     * @title 创建家族
     */
    public function createFamily()
    {
        $user_id = input('get.user_id');
        $userInfo = User::field('nickname,pic,signature,upush_token')->where('id','=',$user_id)->find();

        // 启动事务
        $this->startTrans();
        try {
            $newData = [
                'user_id' => $user_id,
                'f_name' => $userInfo['nickname'].'的家族',
                'f_signature' =>'开黑交友，来绯闻语音噢~',
                'f_pic' => $userInfo['pic'],
                'f_liveness' => 0,
                'create_time' => time(),
                'status' => 1,
                'type'=>1
            ];
            $this->save($newData);
            $familyId = $this->where('user_id','=',$user_id)->value('id');
            $arr = [
                'user_id'=>$user_id,
                'family_id'=>$familyId,
                'check'=>1,
            ];
            $familyMembers = new FamilyMembers();
            $familyMembers->save($arr);

            $info = [
                "user_id" => $user_id,
                'title' => "您已开通家族",
                'content' => "您的账号于".date("Y-m-d H:i:s",time())."开通了家族，有疑问请联系绯闻客服！",
                'have_read' => 1,
                'type' => 2,
                'status' => 1,
                'create_time' => time(),
            ];
            $message = new Message();
            $message->save($info);
            // 提交事务
            $this->commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            $this->rollback();
            return false;
        }
    }

    /**
     * @user shuaisuhi wu
     * @date 2018/12/12
     * @time 14:40
     * @title 开通预审家族
     */
    public function userBuildAgreeFamilyInfo()
    {
        $r_id = input('get.r_id');
        $roomId = Room::where('r_id','=',$r_id)->value('id');
        if(!$roomId) return ['code'=>-100,'msg'=>'没有找到该ID'];

        $familyRoom = FamilyRoom::where('room_id','=',$roomId)->value('id');

        if($familyRoom) return ['code'=>-200,'msg'=>'该房间正在使用'];

        $user_id = input('get.userId');
        $userInfo = User::where('id','=',$user_id)->find();
        // 启动事务
        $this->startTrans();
        try {
            $newData = [
                'user_id' => $user_id,
                'f_name' => $userInfo['nickname'].'的家族',
                'f_signature' =>'开黑交友，来绯闻语音噢~',
                'f_pic' => $userInfo['pic'],
                'f_liveness' => 0,
                'create_time' => time(),
                'status' => 1,
                'type'=>2
            ];
            $this->save($newData);  //返回的不是家族id
            $familyId = $this->where('user_id','=',$user_id)->value('id');
            $arr = [
                'user_id'=>$user_id,
                'family_id'=>$familyId,
                'check'=>1,
                'create_time' => time()
            ];
            $familyMembers = new FamilyMembers();
            $familyMembers->save($arr);


            $array = [
                'family_id' => $familyId,
                'room_id' => $roomId,
                'create_time' => time(),
                'recheck_time' => 0,
                'status' => 1,
            ];
            $familyActivity = new FamilyActivity();
            $familyActivity->save($array);

            $info = [
                "user_id" => $user_id,
                'title' => "您已开通预审家族",
                'content' => "您的账号于".date("Y-m-d H:i:s",time())."开通了家族，有疑问请联系绯闻客服！",
                'have_read' => 1,
                'type' => 2,
                'status' => 1,
                'create_time' => time(),
            ];
            $message = new Message();
            $message->save($info);
            // 提交事务
            $this->commit();
            return ['code'=>100,'msg'=>'创建成功'];
        } catch (\Exception $e) {
            // 回滚事务
            $this->rollback();
            return ['code'=>-300,'msg'=>'创建失败'];
        }
    }

    /**
     * @user shuaisuhai wu
     * @date 2018/12/12
     * @time 17:28
     * @title  解散家族
     */
    public function familyDismiss()
    {
        $familyId = input('get.family_id');
        $userId = input('get.user_id');

        // 启动事务
        $this->startTrans();
        try {

            $this->save(['type'=>4,'status'=>2],['id'=>$familyId]);

            FamilyActivity::where('family_id',$familyId)->update([ 'status' => 4]);

            $userIds = FamilyMembers::field('user_id')->where('family_id','=',$familyId)->select();

            FamilyMembers::where('family_id','=',$familyId)->delete();

            foreach($userIds as $key => $value){
                $info_user = [
                    "user_id" => $value['user_id'],
                    'title' => "您加入家族已解散",
                    'content' => "您的账号于" . date("Y-m-d H:i:s", time()) . "退出了家族，如有疑问请联系绯闻客服！",
                    'have_read' => 1,
                    'type' => 2,
                    'status' => 1,
                    'create_time' => time(),
                ];
                Message::create($info_user);
            }

            $info = [
                "user_id" => $userId,
                'title' => "您的家族已解散",
                'content' => "您的账号于" . date("Y-m-d H:i:s", time()) . "解散了家族，如有疑问请联系绯闻客服！",
                'have_read' => 1,
                'type' => 2,
                'status' => 1,
                'create_time' => time(),
            ];
            Message::create($info);
            // 提交事务
            $this->commit();
            return ['code'=>100,'msg'=>'解散成功'];
        } catch (\Exception $e) {
            // 回滚事务
            $this->rollback();
            return ['code'=>-100,'msg'=>'解散失败'];
        }
    }
}